package com.cungmua.app.activity;

import android.lib.recaptcha.ReCaptcha;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.cungmua.app.R;
import com.cungmua.app.adapter.BonusTransactionAdapter;
import com.cungmua.app.base.BaseDrawerActivitys;
import com.cungmua.app.captcha.Captcha;
import com.cungmua.app.handler.BonusHandler;
import com.cungmua.app.handler.BonusTransactionHandler;
import com.cungmua.app.model.Bonus;
import com.cungmua.app.model.request.BonusRequest;
import com.cungmua.app.model.request.BonusTransactionRequest;
import com.cungmua.app.model.response.BonusResponse;
import com.cungmua.app.model.response.BonusTransactionResponse;
import com.cungmua.app.task.BonusTask;
import com.cungmua.app.task.BonusTransactionTask;
import com.cungmua.app.utils.AppUtils;

/**
 * Created by kelvin.nguyen on 7/1/14.
 */
public class BonusActivity extends BaseDrawerActivitys implements BonusHandler,ReCaptcha.OnShowChallengeListener,BonusTransactionHandler,ReCaptcha.OnVerifyAnswerListener {
    private static final String PUBLIC_KEY = "6LevzPcSAAAAAKk3AES2D4u96c6urENNak5bLu9w";
    private static final String PRIVATE_KEY = "6LevzPcSAAAAAGpd8W7zeEDSkg3djd6VxJ1jvIHa";

    private TextView txtRemain;
    private TextView txtSpent;
    private TextView txtReceived;
    private TextView ans;
    private EditText editTextCaptcha;
    private EditText editTextMaBonus;
    private Captcha c;
    private ReCaptcha reCaptcha;
    private ImageButton reload,btnUsed;
    private ListView listTransactions;
    private BonusTransactionAdapter mAdapter;

    private int currentPage=1;

    @Override
    public int getLayoutResource() {
        return R.layout.activity_bonus;
    }

    @Override
    public void updateView() {
        if (getCurrentUser().getId() == 0) {
            login();
            return;
        }

        BonusRequest request = new BonusRequest(getDeviceId(), getToken());
        request.setUserId(getCurrentUser().getId());
        BonusTask task = new BonusTask(this, this);
        task.execute(request);

        this.showChallenge();


        BonusTransactionRequest bonusTransactionRequest=new BonusTransactionRequest(getDeviceId(),getToken());
        bonusTransactionRequest.setUserId(getCurrentUser().getId());
        bonusTransactionRequest.setPageIndex(currentPage);
        BonusTransactionTask bonusTransactionTask=new BonusTransactionTask(this,this);
        bonusTransactionTask.execute(bonusTransactionRequest);


    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        txtReceived = (TextView) findViewById(R.id.txtReceived);
        txtSpent = (TextView) findViewById(R.id.txtSpent);
        txtRemain = (TextView) findViewById(R.id.txtRemain);
        reCaptcha = (ReCaptcha) findViewById(R.id.recaptcha);
        editTextCaptcha = (EditText) findViewById(R.id.editTextCaptcha);
        editTextMaBonus = (EditText) findViewById(R.id.editTextMaBonus);
        listTransactions = (ListView) findViewById(R.id.listTransactions);
        reload = (ImageButton) findViewById(R.id.reload);
        btnUsed = (ImageButton) findViewById(R.id.btnUsed);

        reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChallenge();
            }
        });

        btnUsed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Spanned error_msg = Html
                        .fromHtml("<font color='red'>Invalid Input captcha" + "</font>");
                verifyAnswer(error_msg);

                if(!validateFields())
                    return;
                BonusRequest request = new BonusRequest(getDeviceId(), getToken());
                request.setUserId(getCurrentUser().getId());
                request.setBonusCode(editTextMaBonus.getText().toString());
                BonusTask task = new BonusTask(BonusActivity.this, BonusActivity.this);
                task.execute(request);

            }
        });
    }
    public boolean validateFields() {
        if (editTextMaBonus.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_bonus));
            return false;
        }
        return true;
    }
    @Override
    public void onBonus(BonusResponse response) {
        Bonus b = response.getData();
        if (b != null) {
            switch (b.getStatus()){
                case 0:
                    txtReceived.setText(getString(R.string.full_price_string,
                            AppUtils.getFullPriceString(b.getMoneyReceived())));
                    txtSpent.setText(getString(R.string.full_price_string,
                            AppUtils.getFullPriceString(b.getMoneyUsed())));
                    txtRemain.setText(getString(R.string.full_price_string,
                            AppUtils.getFullPriceString(b.getMoneyRemain())));
                    break;
                case 1:
                    refreshActivity();
                    break;
                case 2:
                      alert("is not found");
                    break;
                case 3:
                    alert("is Actived");
                    break;
                case 4:
                    alert("expired");
                    break;

            }

        }
    }

    private void showChallenge() {
        // Displays a progress bar while downloading CAPTCHA
        this.reCaptcha.setVisibility(View.VISIBLE);

        this.reCaptcha.showChallengeAsync(this.PUBLIC_KEY, this);
    }

    private void verifyAnswer(Spanned error) {
        if (TextUtils.isEmpty(this.editTextCaptcha.getText())) {
            editTextCaptcha.setError(error);
            editTextCaptcha.requestFocus();
            return;
        } else {
            // Displays a progress bar while submitting the answer for
            // verification
            // this.progress.setVisibility(View.VISIBLE);
            this.reCaptcha.verifyAnswerAsync(this.PRIVATE_KEY,
                    this.editTextCaptcha.getText().toString(), this);
        }
    }

    @Override
    public void onChallengeShown(boolean shown) {
        if (shown) {
            // If a CAPTCHA is shown successfully, displays it for the user to
            // enter the words
            this.reCaptcha.setVisibility(View.VISIBLE);
        } else {
//            Toast.makeText(this, R.string.show_error, Toast.LENGTH_SHORT)
//                    .show();
        }
    }

    @Override
    public void onAnswerVerified(boolean success) {
        Spanned error_msg = Html
                .fromHtml("<font color='red'>Invalid Input captcha" + "</font>");
        if (success) {
            //Toast.makeText(this, "Corrected",
//                    Toast.LENGTH_SHORT).show();

        } else {
            verifyAnswer(error_msg);
//            Toast.makeText(this, "not correct",
//                    Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onBonusTransaction(BonusTransactionResponse response) {
        if (response.getData() != null) {
            if (response.getData().size() > 0) {
                mAdapter=new BonusTransactionAdapter(this,this,response.getData());
                listTransactions.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                AppUtils.setListViewHeightBasedOnChildren(listTransactions);
            } else {
                listTransactions.setEmptyView(findViewById(R.id.txtEmptyTransactions));
            }
        }
    }
}
